<?php

/* Inlude des autres fichiers de fonctions */
include('wpspo_functions_users.php');
include('wpspo_functions_files.php');
include('wpspo_functions_forms.php');

/* 
 * Réécriture personnalisée des URL
 * Personnalise si par de projet choisi
 * Personnalise organise un défi suivant un projet
 */

add_action('init', 'wpspo_add_my_rewrite_projets');
function wpspo_add_my_rewrite_projets() {
  global $wp_rewrite;
  add_rewrite_tag('%choixprojet%', '([^&]+)');
  add_rewrite_tag('%participant%', '([^&]+)');
  $wp_rewrite->add_rule(get_page(WPSPO_ID_PROJETS)->post_name.'/'.__('choose-a-project','sponsorpress').'', 'index.php?pagename='.get_page(WPSPO_ID_PROJETS)->post_name.'&choixprojet=1', 'top');
  $wp_rewrite->add_rule(get_page(WPSPO_ID_ORGANISER)->post_name.'/([^/]+)', 'index.php?pagename='.get_page(WPSPO_ID_ORGANISER)->post_name.'&choixprojet=$matches[1]', 'top');
  $wp_rewrite->flush_rules();
}

function wpspo_content_traitement($email_content, $args = '', $sign = 1) {
    
    if($email_content) {
        
        if(get_option('wpspo_emails_settings')) { extract(get_option('wpspo_emails_settings')); }
        $paramWpspoEmailSetting = get_option('wpspo_emails_settings');
        
         // traitement du contenu de l'email 
        $remplacements = array (
            "#_LOGIN" => $current_user->user_login,
            "#_DEFI" => '<a href="'.get_permalink($args['ID']).'"><b>'.get_the_title($args['ID']).'</b></a>',
            "#_LINK_DEFI" => get_permalink($args['ID']),
            "#_PROJET" => '<a href="'.get_permalink($_POST["wpspo_choixprojets"]).'"><b>'.get_page($_POST["wpspo_choixprojets"])->post_title.'</b></a>',
            "#_LINK_PROJET" => get_permalink($_POST["wpspo_choixprojets"]),
            "#_LINK_ESPACEPERSO" => get_permalink(WPSPO_ID_COMPTE),
            "#_LINK_CONTACT" => get_permalink(get_option('wp_sponsorpress_contact')),
            "#_SITE" => esc_attr( get_bloginfo( 'name', 'display' ) ),
            "#_LINK_SITE" => esc_url( home_url( '/' ) ),
            
        );
        if($args) {$remplacements = array_merge($remplacements, $args); }
        $email_content = str_replace(array_keys($remplacements), array_values($remplacements), $email_content);	
            
        if($paramWpspoEmailSetting['email_txt_signature']!='' && $sign==1) {
            $email_signature = str_replace(array_keys($remplacements), array_values($remplacements), $paramWpspoEmailSetting['email_txt_signature']);
            $email_content .= '<br /><br />'.$email_signature;
        }

        return $email_content;
        
    } /*else {
        
        return 'NO CONTENT EMAIL';
    }*/
    
}
/* 
 * Désactive les box de l'adminitration 
 */
function wpspo_disable_default_dashboard_widgets() {
	remove_meta_box('dashboard_right_now', 'dashboard', 'core');
	remove_meta_box('dashboard_recent_comments', 'dashboard', 'core');
	remove_meta_box('dashboard_incoming_links', 'dashboard', 'core');
	remove_meta_box('dashboard_plugins', 'dashboard', 'core');
	remove_meta_box('dashboard_quick_press', 'dashboard', 'core');
	remove_meta_box('dashboard_recent_drafts', 'dashboard', 'core');
	remove_meta_box('dashboard_primary', 'dashboard', 'core');			// Autres news WordPress
	remove_meta_box('dashboard_secondary', 'dashboard', 'core');			// News WordPress
}
add_action('admin_menu', 'wpspo_disable_default_dashboard_widgets');


/*
 * Liste les widgets du dasboard
 *//*
function list_active_dashboard_widgets() {
	global $wp_meta_boxes;
	foreach (array_keys($wp_meta_boxes['dashboard']['normal']['core']) as $name) {
		echo '<div>' . $name . '</div>';
	}
}
add_action('wp_dashboard_setup', 'list_active_dashboard_widgets');
*/
//wp_enqueue_script('jquery-ui-datepicker');


/*
 * Entete pour le date picker
 *  Trouvé ici :http://www.zigpress.com/2011/04/27/jquery-ui-datepicker-in-wordpress-admin/
 */
function wpspo_admin_init() {
	wp_enqueue_script('jquery');
    wp_enqueue_script('common');
    wp_enqueue_script('wp-lists');
    wp_enqueue_script('postbox');
}
add_action('admin_init', 'wpspo_admin_init'); 

function wpspo_admin_scripts() { 
    wp_enqueue_script('media-upload'); 
    wp_enqueue_script('thickbox'); 
    wp_register_script('my-upload', WP_PLUGIN_URL.'/'.WPSPO_NAME_DIR.'/wpspo-js/wpspo_scripts.js', array('jquery','media-upload','thickbox')); 
    wp_register_script('admin-settings', WP_PLUGIN_URL.'/'.WPSPO_NAME_DIR.'/wpspo-js/wpspo-admin-settings.js'); 
    wp_enqueue_script('admin-settings');
    wp_enqueue_script('my-upload'); 
}  
function wpspo_admin_styles() { 
    wp_enqueue_style('thickbox'); 
}  
/* DATEPICKER */
add_action( 'init', 'wpspo_date_picker' );
function wpspo_date_picker() {
    wp_enqueue_script( 'jquery' );
    //wp_enqueue_script( 'jquery-ui-core' );
    //wp_enqueue_script('jquery-ui-datepicker');
    wp_enqueue_script( 'jquery-datepicker', WP_PLUGIN_URL.'/'.WPSPO_NAME_DIR.'/wpspo-js/jquery.ui.datepicker.min.js', array('jquery', 'jquery-ui-core' ) );
    //wp_enqueue_script('jquery-ui-fr-datepicker', WP_PLUGIN_URL.'/'.WPSPO_NAME_DIR.'/wpspo-js/jquery.ui.datepicker-fr.js', array('jquery-ui-datepicker'));
    wp_enqueue_style('jquery-style', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/themes/smoothness/jquery-ui.css');
    
}
//if( is_page(WPSPO_ID_ORGANISER) ) {
add_action( 'wp_footer', 'wpspo_print_scripts');
//}
function wpspo_print_scripts() {
    
    if( is_page(WPSPO_ID_ORGANISER) ) {
        if(get_option('wpspo_plugin_settings')) { extract(get_option('wpspo_plugin_settings')); }
        $paramWpspoSetting = get_option('wpspo_plugin_settings');
        $imgCalendar = WP_PLUGIN_URL.'/'.WPSPO_NAME_DIR.'/wpspo-images/calendar2.png';
    ?>
<script src="<?php echo WP_PLUGIN_URL.'/'.WPSPO_NAME_DIR ?>/wpspo-js/jquery.ui.datepicker-fr.js" type="text/javascript"></script>
<script type="text/javascript">
    jQuery(document).ready(function() {
       jQuery('.DateDefi').datepicker({
            dateFormat : 'dd-mm-yy',
            minDate: "+<?php echo $paramWpspoSetting['limitdate']; ?>",
            maxDate: "+12M",
            regional:"fr",
            showButtonPanel: true,
            showOn: "button",
            buttonImage: "<?php echo $imgCalendar; ?>",
            buttonImageOnly: true,
            /*onClose: function (dateText, inst) {
                var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
                var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
                $(this).datepicker('setDate', new Date(year, month, 1));
            },*/
            
        });
    });
</script>
    <?php
    }
}
/* END DATEPICKER */

if (isset($_GET['page']) && $_GET['page'] == 'sponsor-settings') { 
    add_action('admin_print_scripts', 'wpspo_admin_scripts'); 
    add_action('admin_print_styles', 'wpspo_admin_styles'); 
}
/*add_action('init', 'wpspo_admin_scripts'); 
add_action('init', 'wpspo_admin_styles'); */
/*
 * Ajoute des widgets sur le dashboard
 */
function wpspo_no_update_widget() {
	echo '<p><b>Info ici :</b> Toutes les infos ici<br />';
}
function wpspo_listprojet_widget() {
    
   //echo wpsp_listprojets_function(1);
   echo '<br /><br /><div style="text-align:right;"><a href="/wp-admin/edit.php?post_type=projets">Voir la liste des projets</a></div>';
}
function wpspo_dashboard_widgets() {
	if ( current_user_can('update_core') )
    wp_add_dashboard_widget('custom_help_widget1', 'Modifications et plugins à ne pas mettre à jour', 'wpspo_no_update_widget');
	wp_add_dashboard_widget('custom_help_widget2', 'Listes des projets', 'wpspo_listprojet_widget');
}
add_action('wp_dashboard_setup', 'wpspo_dashboard_widgets');

/* 
 * Fonction pour afficher des boutons 
 */
function wpspobutton_print($text = 'Text du bouton', $taille = '100', $color = 'orange', $link = '', $addlink = '') {
    if($link=='') { $link = get_post_permalink(); }
  //processus du plugin
   return '<div style="text-align:center;"><a style="color:white;" class="wpspo-bouton medium '.$color.'" '.$addlink.' href="'.$link.'">'.$text.'</a></div>';
}

/*
 *  Fonction pour retourner les infos du projet
 */
function wpspobutton_infos_project() {
    
    global $post;
    
    if($link=='') { $link = get_post_permalink(); }
    
    $countDefi[$post->ID] = WPSPO_Defis::get_countByProjet(get_the_id());
    // Compte de nombre de participant
    $countNbParticipant[$post->ID] = WPSPO_Promesse::get_countByProjet($post->ID);
    
    $infosProject = '<div class="clear espace10">&nbsp;</div>';
        $infosProject .= '<div id="campaign-'.$post->ID.'" class ="featured-campaign">';
            $infosProject .= '<ul class="campaign-status horizontal">';

                $valueObjectif[$post->ID] = get_post_meta($post->ID, 'wpspo_boxprojets', true); // Récupère l'objectif cible
                if($valueObjectif[$post->ID]>1){
                    $infosProject .= '<li>';
                    $infosProject .= wpspo_price($valueObjectif[$post->ID]).'<br /><small>'.__( 'Goal' , 'sponsorpress').'</small></li>';
                }
                $infosProject .= '<li>';
                   $totalPromesse[$post->ID] = WPSPO_Promesse::get_sum($id, 1);  // Récupère les promesses FIXES
                    $infosProject .= wpspo_price($totalPromesse[$post->ID]).'<br /><small>'.__( 'Funded' , 'sponsorpress').'</small></li>';

                $infosProject .= '<li>';
                    $infosProject .= sprintf(_n("%s<br /><small>".__( 'challenge' , 'sponsorpress')."</small>", "%s<br /><small>".__( 'challenges' , 'sponsorpress')."</small>", $countDefi[$post->ID], 'sponsorpress'), $countDefi[$post->ID]);
                $infosProject .= '</li>';

                $infosProject .= '<li>';
                    //if($countNbParticipant>=1) {
                    $infosProject .= sprintf(_n("%s<br /> <small>contributor</small>", "%s<br /> <small>contributors</small>", $countNbParticipant[$post->ID], 'sponsorpress'), $countNbParticipant[$post->ID]);
                    //}
                $infosProject .= '</li>';

            $infosProject .= '</ul>';
        $infosProject .= '</div>';
    return $infosProject;
}

function wpspobutton_widget_print ($text = 'Text du bouton', $taille = '100', $color = '#E15821', $link = '/') {

    return '<div class="conteneurbouton">
        <a class="wpspo-bouton-carre" href="'.$link.'" style="background-color:'.$color.';color:#fff;width:'.$taille.'px;">
            '.$text.'
        </a>
    </div>';
}

function wpspobutton_print_big($text = 'Text du bouton', $taille = '140', $color = 'orange') {
  //processus du plugin
   return '<div class="conteneurbouton" style="width:'.$taille.'px;height:'.$taille.'px;line-height:'.$taille.'px;"><div class="blocbouton bg-'.$color.'"><a class="wpspo-bouton-carre" href="'.get_post_permalink().'">'.$text.'</a></div></div>';
}

function wpspobutton_print_icon($text = 'Text du bouton', $link = '', $icon = 'map', $taille = '140', $color = 'orange') {
  //processus du plugin
   $srcImg = WPSPO_URL.'/wpspo-themes/default/images/'.$icon.'.png';
   if($link=='') { $link = get_post_permalink(); }
   return '<div class="conteneurbouton" style="width:'.$taille.'px;height:'.$taille.'px;line-height:'.$taille.'px;">
               <div class="blocbouton bg-'.$color.'">
                   <a class="wpspo-bouton-carre" href="'.$link.'"><img src='.$srcImg.' /><br />'.$text.'</a>
               </div>
           </div>';
}


/*
  * Function pour les templates de thème
  */
function wpspo_include_template($display_type = 'default', $src = 0) {
    
    if($src == 0) {
        include (WPSPO_FILE_PATH.'/wpspo-themes/default/tp-wpspo-'.$display_type.'.php');
    } else {
        include (WPSPO_FILE_PATH.'/wpspo-themes/wpspo-'.$display_type.'.php');
    }
}


/*
 * filter for PAGES - Dirige vers un template spéciale
 */
add_filter( 'page_template', 'wpspo_custom_page_template' );
function wpspo_custom_page_template( $page_template ) {
    
    if ( is_page( WPSPO_ID_ORGANISER ) ) {
        $page_template = WP_PLUGIN_DIR.'/'.WPSPO_NAME_DIR.'/wpspo-themes/default/tp-wpspo-organiser.php'; 
    }
    if( is_page( WPSPO_ID_PROJETS ) ) {
        $page_template = WP_PLUGIN_DIR.'/'.WPSPO_NAME_DIR.'/wpspo-themes/default/tp-wpspo-projets.php';
    }
    if( is_page( WPSPO_ID_DEFIS ) ) {
        $page_template = WP_PLUGIN_DIR.'/'.WPSPO_NAME_DIR.'/wpspo-themes/default/tp-wpspo-defis.php';
    }
    if( is_page( WPSPO_ID_COMPTE ) ) {
        $page_template = WP_PLUGIN_DIR.'/'.WPSPO_NAME_DIR.'/wpspo-themes/default/tp-wpspo-profil.php';
    }
    if( is_page( WPSPO_ID_ARCHIVES ) ) {
        $page_template = WP_PLUGIN_DIR.'/'.WPSPO_NAME_DIR.'/wpspo-themes/default/tp-wpspo-archives.php';
    }
    if( is_page( WPSPO_ID_PARTICIPANTS ) ) {
        $page_template = WP_PLUGIN_DIR.'/'.WPSPO_NAME_DIR.'/wpspo-themes/default/tp-wpspo-participants.php';
    }
    return $page_template;
}
/*
 * Filter for SINGLE PAGE - Dirige les custom post type Défi / Projets  vers templates Single Perso
 */
function wpspo_get_custom_post_type_template($single_template) {
     global $post;
//print_r($post);
     if ($post->post_type == 'defi') {
          $single_template = WP_PLUGIN_DIR.'/'.WPSPO_NAME_DIR.'/wpspo-themes/default/tp-wpspo-single-defi.php';
     }
     if ($post->post_type == 'projet') {
        if ($post->post_status == 'archive') {
            $single_template = WP_PLUGIN_DIR.'/'.WPSPO_NAME_DIR.'/wpspo-themes/default/tp-wpspo-single-archive.php';
        } else {
            $single_template = WP_PLUGIN_DIR.'/'.WPSPO_NAME_DIR.'/wpspo-themes/default/tp-wpspo-single-projet.php';
        }
     }

     return $single_template;
}
add_filter( "single_template", "wpspo_get_custom_post_type_template" ) ;

/*
 * 
 */
function wpspo_type_defi($nb = '') {
    /* TODO : list avec $paramWpspoSetting['listtypedefi'] */
    $typeDefi = array(
        __('A particular', 'sponsorpress') => 1,
        __('A youth group', 'sponsorpress') => 2,
        __('A colony', 'sponsorpress') => 3,
        __('A association', 'sponsorpress') => 4,
    );
    if(is_numeric($nb)) {
        return array_search($nb, $typeDefi);
    } else {
        return $typeDefi;
    }
    
}

function wpspo_display_date($startdate, $enddate = '') {
    
    /* Configure le script en français */
    setlocale (LC_TIME, 'fr_FR','fra');
    //Définit le décalage horaire par défaut de toutes les fonctions date/heure  
    date_default_timezone_set("Europe/Paris");
    //Definit l'encodage interne
    //mb_internal_encoding("UTF-8");
    mb_internal_encoding("iso-8859-1");

    if($enddate) {
        $returnDate = 'Du '.strftime('%d', strtotime($startdate)).' au '.strftime('%d %B %Y', strtotime($enddate));
    } else {
        $returnDate =  'Le '.strftime('%d %B %Y', strtotime($startdate));
    }    
    return $returnDate;
}
/*
 * Compare des dates
 */
function wpspo_compare_date($date, $print=0) {
    $datejour = date('d/m/Y');
    
    //explode pour mettre la date du fin en format numerique: 12/05/2006  -> 12052006
    $dfin = explode("-", $date); 
    
    //explode pour mettre la date du jour en format numerique: 31/05/2009  -> 31052009
    $djour = explode("/", $datejour); 
        
    // concaténation pour inverser l'ordre: 12052006 -> 20060512
    $finab = $dfin[2].$dfin[1].$dfin[0]; 
    // concaténation pour inverser l'ordre: 31052009 -> 20090531
    $auj = $djour[2].$djour[1].$djour[0]; 
 
    // Ensuite il suffit de comparer les deux valeurs
 
    if ($auj>$finab) {
        //------Abonnement expiré;-------
        if($print==1) {
            return 'Expiré';
        } else {
            return false; 
        }
    } else {
        //-------Abonnement en cours-----
        if($print==1) {
            return 'En cours';
        } else {
            return true;
        }
    }
}

/*
 * Ajout des champs personnalisés pour les Custom Post Type
 */
add_action('wp_insert_post', 'wpspo_champs_personnalises_defaut');
function wpspo_champs_personnalises_defaut($post_id) {
    global $typenow;
     if ( $typenow == 'projet' )  {
         add_post_meta($post_id, 'wpspo_boxprojets', '', true);
         add_post_meta($post_id, 'wpspo_boxdateend', '', true);
         add_post_meta($post_id, 'wpspo_boxnodate', '', true);
         add_post_meta($post_id, 'wpspo_boxclose', '', true);
     } elseif( $typenow == 'defi' ) {
         add_post_meta($post_id, 'wpspo_choixprojets', '', true);
         add_post_meta($post_id, 'wpspo_typedefi', '', true);
     }
     //add_post_meta($post_id, 'wpspo_fied1', 'Champ1', true);
     return true;
 }

function wpspo_listepays($getIso) {

    $pays = array(
        'ZA' => 'Afrique Francophone',
        'BE' => 'Belgique',
        'CA' => 'Canada',
        'FR' => 'France',
        'GP' => 'Guadeloupe',
        'GF' => 'Guyane française',
        'LU' => 'Luxembourg',
        'MQ' => 'Martinique',
        'MC' => 'Monaco',
        'NC' => 'Nouvelle-Calédonie',
        'RE' => 'La Réunion',
        'PF' => 'Polynésie française',
        'CH' => 'Suisse'
    );
    if ($getIso && array_key_exists($getIso, $pays)) {
        $pays = $pays[$getIso];
    }
    return $pays;
}

/*
 * Liste des défis sous les post projets
 */
function wpspo_listing_defis($idProjet) {
    
    $list = WPSPO_Defis::listByProjet($idProjet);

    if(count($list)>=1) {
        
        $out .= '<div class="clear espace15"></div><h1 class="wpspo-title">';
        $out .= sprintf(_n("%s Challenge proposed", "%s Challenges proposed", count($list), 'sponsorpress'), count($list));
        $out .= '</h1><hr/>';

        foreach($list as $lesDefis) {
            
            $countNbParticipant = WPSPO_Users::get_count($lesDefis->ID);
            
            $dateDefis = strftime('%d %m %Y', strtotime($lesDefis->post_date));
            $out .= '<div style="float:left;width:12%;line-height:1.4em;"><small>'.__('Posted on', 'sponsorpress').'<br /> <b>'.$dateDefis.'</b></small></div>';
            $out .= '<div style="float:left;width:20%;"><div style="display: inline-block;list-style: none;margin-right: 5px;text-decoration: none;clear: both;padding: 8.5px 15px;border-radius: 4px;-webkit-border-radius: 4px;background-color:#E15821;color:#FFFFFF;margin-top: 5px;font-size: 0.8em;text-align: center">';
            $out .= sprintf(_n("%s contributor", "%s contributors", $countNbParticipant, 'sponsorpress'), $countNbParticipant);
            $out .= '</div></div>';
            $out .= '<div style="float:left;width:60%;line-height:1.4em; font-size:11pt;"><a href="'.get_permalink($lesDefis->ID).'" style="text-decoration:underline;">'.$lesDefis->post_title.'</a><br />'.wpspo_cutString($lesDefis->post_content, 0, 225, ' <a href="'.get_permalink($lesDefis->ID).'">[...]</a>').'</div>';
            $out .= '<div style="float:left;width:6%;line-height:1.4em;"><a href="'.get_permalink($lesDefis->ID).'"><img src="'.WPSPO_IMG_URL.'icon-arrow.png" alt="'.$lesDefis->post_title.'" title="'.$lesDefis->post_title.'" /></a></div>';
            $out .= '<div class="clear espace15 trait"></div>'; 
            
        }
        
    } else {
        
        $out .= '<h3 class="wpspo-title">'.__('No challenge proposed', 'sponsorpress').'</h3>';
        $out .= '<a href="'.get_permalink(WPSPO_ID_ORGANISER).WPSPO_LINK_PROJECT.sanitize_title(get_the_title()).'">'.__('Be the first to organize a challenge for this project', 'sponsorpress').'</a>';
        
    }
    //print_r($list[1]);
    return $out;
}

/*
 * Couper le texte
 */
function wpspo_cutString($string, $start, $length, $endStr = '[...]'){  
    // si la taille de la chaine est inférieure ou égale à celle  
    // attendue on la retourne telle qu'elle  
    if( strlen( $string ) <= $length ) return $string;  
    // autrement on continue  
    // permet de couper la phrase aux caractères définis tout  
    // en prenant en compte la taille de votre $endStr et en  
    // re-précisant l'encodage du contenu récupéré  
    $str = mb_substr( $string, $start, $length - strlen( $endStr ) + 1, 'UTF-8');  
    // retourne la chaîne coupée avant la dernière espace rencontrée  
    // à laquelle s'ajoute notre $endStr  
    return substr( $str, 0, strrpos( $str,' ') ).$endStr;  
}

/*
 * Affiche au pluriel //TODO : A voir pas terrible
 */
if( !function_exists( 'wpspo_pluriel' ) ) {
    function wpspo_pluriel($nb = 0, $txtif1 = "", $txtif2 = "", $aucun = "Aucun") {
        if($nb<1) { 
            $texte = $aucun."&nbsp;".$txtif1;
        } elseif($nb==1) { 
            $texte = $nb."&nbsp;".$txtif1;
        } else { 
            $texte = $nb."&nbsp;".$txtif2; 
        }
        return $texte;
    }
}
    
/*
 * Re-générer un slug en cas de modification du titre du défi
 */
if( !function_exists( 'wpspo_generate_slug' ) ) {
    function wpspo_generate_slug($str) {
        $maxlen = 42;  //Modifier la taille max du slug ici
        $slug = strtolower($str);

        $slug = preg_replace("/[^a-z0-9\s-]/", "", $slug);
        $slug = trim(preg_replace("/[\s-]+/", " ", $slug));
        $slug = preg_replace("/\s/", "-", $slug);

        return $slug;
    }
}

/*
 * Pagination perso
 */
if( !function_exists( 'wpspo_theme_pagination' ) ) {
    function wpspo_theme_pagination() {
        global $wp_query, $wp_rewrite;
        $wp_query->query_vars['paged'] > 1 ? $current = $wp_query->query_vars['paged'] : $current = 1;
        $pagination = array(
            'base' => @add_query_arg('page','%#%'),
            'format' => '',
            'total' => $wp_query->max_num_pages,
            'current' => $current,
            'show_all' => false,
            'end_size' => 1,
            'mid_size' => 2,
            'type' => 'list',
            'next_text' => '»',
            'prev_text' => '«'
        );
        if( $wp_rewrite->using_permalinks() )
            $pagination['base'] = user_trailingslashit( trailingslashit( remove_query_arg( 's', get_pagenum_link( 1 ) ) ) . 'page/%#%/', 'paged' );
        if( !empty($wp_query->query_vars['s']) )
            $pagination['add_args'] = array( 's' => str_replace( ' ' , '+', get_query_var( 's' ) ) );
        echo '<div id="wpspo_pagination">';
        echo str_replace('page/1/','', paginate_links( $pagination ) );
        echo '</div>';
       
    }	
}

// Fonction de redirection
if( !function_exists( 'wpspo_redirection' ) ) {
    function wpspo_redirection($redirect = "/", $type = "") {
        /*setTimeout('top.location.href="<?php echo get_permalink(WPSPO_ID_PROJETS); ?>"', 2000)*/
        if($type=="js") {
            $out = '<script language="javascript">window.location.replace("'.$redirect.'");</script>';
        } else {
            header("location: ".$redirect."");
        }
        return $out;
    }
}


/*
 * Statut pour archive
 */
if ( ! function_exists('wpspo_post_status') ) {

    // Register Custom Status
    function wpspo_post_status() {

        $args = array(
            'label'                     => _x( 'Archive', 'Status General Name', 'sponsorpress' ),
            'label_count'               => _n_noop( 'archive (%s)',  'archives (%s)', 'sponsorpress' ), 
            'public'                    => true,
            'show_in_admin_all_list'    => true,
            'show_in_admin_status_list' => true,
            'exclude_from_search'       => false,
        );
        register_post_status( 'Archive', $args );

    }

    // Hook into the 'init' action
    add_action( 'init', 'wpspo_post_status', 0 );

}

/*
 * Fonction qui retourne le post via son post_name
 */
function get_post_by_name($page_name, $post_type = 'projet', $output = OBJECT) {
    
    global $wpdb;
    $post = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE post_name='".$page_name."' AND post_type='".$post_type."'", $page_title ), $output);
    
    if ( $post )
        return $post;
 
    return null;
}

/*
 *  Fonction rewrite pour les custom post type
 */

add_filter('generate_rewrite_rules', 'wpspo_customposttype_rewrites');
function wpspo_customposttype_rewrites($wp_rewrite) {
    $newrules = array();
    $newrules['projet/?$'] = 'index.php?post_type=projet';
    $wp_rewrite->rules = $newrules + $wp_rewrite->rules;
}

/* fonction pour la monnaie*/
function get_wpspo_currency() {
	return apply_filters( 'wpspo_currency', get_option('wpspo_currency') );
}
function get_wpspo_currencies() {
	return array_unique(
		apply_filters( 'woocommerce_currencies',
			array(
				'AUD' => 'Australian Dollars',
				'BRL' => 'Brazilian Real',
				'CAD' => 'Canadian Dollars',
				'RMB' => 'Chinese Yuan',
				'CZK' => 'Czech Koruna',
				'DKK' => 'Danish Krone',
				'EUR' => 'Euros',
				'HKD' => 'Hong Kong Dollar',
				'HUF' => 'Hungarian Forint',
				'IDR' => 'Indonesia Rupiah',
				'INR' => 'Indian Rupee',
				'ILS' => 'Israeli Shekel',
				'JPY' => 'Japanese Yen',
				'KRW' => 'South Korean Won',
				'MYR' => 'Malaysian Ringgits',
				'MXN' => 'Mexican Peso',
				'NOK' => 'Norwegian Krone',
				'NZD' => 'New Zealand Dollar',
				'PHP' => 'Philippine Pesos',
				'PLN' => 'Polish Zloty',
				'GBP' => 'Pounds Sterling',
				'RON' => 'Romanian Leu',
				'RUB' => 'Russian Ruble',
				'SGD' => 'Singapore Dollar',
				'ZAR' => 'South African rand',
				'SEK' => 'Swedish Krona',
				'CHF' => 'Swiss Franc',
				'TWD' => 'Taiwan New Dollars',
				'THB' => 'Thai Baht',
				'TRY' => 'Turkish Lira',
				'USD' => 'US Dollars',
			)
		)
	);
}
function get_wpspo_currency_symbol( $currency = '' ) {
	if ( ! $currency )
		$currency = get_wpspo_currency();

	switch ( $currency ) {
		case 'BRL' :
			$currency_symbol = '&#82;&#36;';
			break;
		case 'AUD' :
		case 'CAD' :
		case 'MXN' :
		case 'NZD' :
		case 'HKD' :
		case 'SGD' :
		case 'USD' :
			$currency_symbol = '&#36;';
			break;
		case 'EUR' :
			$currency_symbol = '&euro;';
			break;
		case 'CNY' :
		case 'RMB' :
		case 'JPY' :
			$currency_symbol = '&yen;';
			break;
		case 'RUB' :
			$currency_symbol = '&#1088;&#1091;&#1073;.';
			break;
		case 'KRW' : $currency_symbol = '&#8361;'; break;
		case 'TRY' : $currency_symbol = '&#84;&#76;'; break;
		case 'NOK' : $currency_symbol = '&#107;&#114;'; break;
		case 'ZAR' : $currency_symbol = '&#82;'; break;
		case 'CZK' : $currency_symbol = '&#75;&#269;'; break;
		case 'MYR' : $currency_symbol = '&#82;&#77;'; break;
		case 'DKK' : $currency_symbol = '&#107;&#114;'; break;
		case 'HUF' : $currency_symbol = '&#70;&#116;'; break;
		case 'IDR' : $currency_symbol = 'Rp'; break;
		case 'INR' : $currency_symbol = '&#8377;'; break;
		case 'ILS' : $currency_symbol = '&#8362;'; break;
		case 'PHP' : $currency_symbol = '&#8369;'; break;
		case 'PLN' : $currency_symbol = '&#122;&#322;'; break;
		case 'SEK' : $currency_symbol = '&#107;&#114;'; break;
		case 'CHF' : $currency_symbol = '&#67;&#72;&#70;'; break;
		case 'TWD' : $currency_symbol = '&#78;&#84;&#36;'; break;
		case 'THB' : $currency_symbol = '&#3647;'; break;
		case 'GBP' : $currency_symbol = '&pound;'; break;
		case 'RON' : $currency_symbol = 'lei'; break;
		default    : $currency_symbol = ''; break;
	}

	return apply_filters( 'wpspo_currency_symbol', $currency_symbol, $currency );
}
function wpspo_price( $price, $args = array(), $format = 1 ) {


	extract( shortcode_atts( array(
		'wpspo_tax_label' 	=> '0'
	), $args ) );

	$return          = '';
	$currency_pos    = get_option( 'wpspo_currency_pos' );
	$currency_symbol = get_wpspo_currency_symbol();

	if ( get_option( 'wpspo_price_trim_zeros' ) == 'yes' ) {
		$price = wpspo_trim_zeros( $price );
    }
    if($format==1) {
        $return = '<span class="amount">' . sprintf( get_wpspo_price_format(), $currency_symbol, $price ) . '</span>';
    } else {
        $return = sprintf( get_wpspo_price_format(), $currency_symbol, $price );
    }
	return $return;
}

function get_wpspo_price_format() {
	$currency_pos = get_option( 'wpspo_currency_pos' );

	switch ( $currency_pos ) {
		case 'left' :
			$format = '%1$s%2$s';
		break;
		case 'right' :
			$format = '%2$s%1$s';
		break;
		case 'left_space' :
			$format = '%1$s&nbsp;%2$s';
		break;
		case 'right_space' :
			$format = '%2$s&nbsp;%1$s';
		break;
	}

	return apply_filters( 'wpspo_price_format', $format, $currency_pos );
}
function wpspo_trim_zeros( $price ) {
	return preg_replace( '/' . preg_quote( '.', '/' ) . '0++$/', '', $price );
}


